package jmine.tec.utils.io;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * {@link FilterInputStream} que fecha o {@link InputStream} quando chegar ao final do stream
 * 
 * @author takeshi
 */
public class AutoCloseInputStream extends FilterInputStream {

    /**
     * C'tor
     * 
     * @param in o {@link FilterInputStream}
     */
    public AutoCloseInputStream(InputStream in) {
        super(in);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int read() throws IOException {
        int read = super.read();
        if (read < 0) {
            close();
        }
        return read;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int read(byte[] b) throws IOException {
        int read = super.read(b);
        if (read < 0) {
            close();
        }
        return read;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int read = super.read(b, off, len);
        if (read < 0) {
            close();
        }
        return read;
    }

}
